import React,{ useState,useEffect } from 'react'
import { withRouter } from 'react-router-dom';
import { Button,Modal,Popover } from 'antd';
import { removeUser } from '../../utils/storageUtils';
import { reqGetSite,reqGetWeather } from '../../api/index';
import Clock from '../Clock/Clock'
import './Header.css'
import getWeatherIcon from '../../utils/getWeatherIcon'

import { connect } from 'react-redux';

import { resetUser } from '../../redux/actions';

export default connect(state=>({headTitle:state.headTitle,user:state.user}),{resetUser})(withRouter( function Header(props) {

  const [isModalVisible,setIsModalVisible] = useState(false)
  const [weather,setWeather] = useState({})
  const [weatherIcon,setWeatherIcon] = useState({})
  const [weatherInfo,setWeatherInfo] = useState(<></>)

  const { username,name } = props.user

  const handleOk=()=>{
    setIsModalVisible(false)
    props.resetUser()
    removeUser()
    window.location.reload()
  }

  useEffect(()=>{
    async function fetchData(){
      let res=await reqGetSite()
      let city=res.data.adcode
      let _weather=await reqGetWeather(city)
      console.log(_weather)
      _weather=_weather.data.lives[0]
      setWeather(_weather)
      let _weatherIcon=await getWeatherIcon(_weather.weather)
      setWeatherIcon(_weatherIcon.default)
      setWeatherInfo((
        <div>
          <p className='weather-content'>{_weather.temperature+'℃'}</p>
          <p className='weather-content'>{_weather.weather}</p>
          <p className='weather-content'>{_weather.winddirection+'风 '+_weather.windpower+'级'}</p>
          <p className='weather-content'>{_weather.humidity+' 湿度' }</p>
        </div>
      ))
    }
    fetchData()
  },[])

  return (
    <div className='header'>
      <div className='header-top'>
        <div className='header-logout'>欢迎 {name?name:username} <Button type="link" onClick={()=>setIsModalVisible(true)}>退出</Button></div>
      </div>
      <div className='header-bot'>
        <div className='header-title'>{props.headTitle}</div>
        <div className='header-right'>
          <Clock/>
          <span className='header-weather'>{weather.province?(weather.province+'·'+weather.city+' '+weather.weather):'正在获取...'}</span>
          {
            JSON.stringify(weatherIcon)!=='{}'?(
              <Popover placement="bottomLeft" content={weatherInfo} trigger="hover">
                <img src={weatherIcon} alt="" />
              </Popover>
            ):<span>正在获取...</span>
          }
          
        </div>
      </div>
      <Modal title="退出" visible={isModalVisible} onOk={handleOk} onCancel={()=>setIsModalVisible(false)}>
        <p>是否要退出当前账号？</p>
      </Modal>
    </div>
  )
}))
